package com.djf.djfcs.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.djf.djfcs.entity.Product;
import com.djf.djfcs.mapper.ProductMapper;
import com.djf.djfcs.service.IProductService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 商品服务实现类
 * 继承ServiceImpl，实现IProductService接口
 * 提供商品的完整CRUD操作和批量操作
 */
@Slf4j
@Service
public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product> implements IProductService {

    /**
     * 创建商品
     */
    public Product createProduct(Product product) {
        product.setCreateTime(LocalDateTime.now());
        product.setUpdateTime(LocalDateTime.now());
        product.setDeleted(0);
        
        boolean result = save(product);
        if (result) {
            log.info("商品创建成功，商品ID：{}，商品编码：{}", product.getId(), product.getProductCode());
            return product;
        } else {
            throw new RuntimeException("商品创建失败");
        }
    }

    /**
     * 根据ID查询商品
     */
    public Product getProductById(Long id) {
        return getById(id);
    }

    /**
     * 根据商品编码查询商品
     */
    @Override
    public Product getProductByCode(String productCode) {
        QueryWrapper<Product> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("product_code", productCode)
                   .eq("deleted", 0);
        return getOne(queryWrapper);
    }

    /**
     * 更新商品
     */
    public Product updateProduct(Product product) {
        product.setUpdateTime(LocalDateTime.now());
        
        boolean result = updateById(product);
        if (result) {
            log.info("商品更新成功，商品ID：{}", product.getId());
            return product;
        } else {
            throw new RuntimeException("商品更新失败");
        }
    }

    /**
     * 删除商品（逻辑删除）
     */
    public boolean deleteProduct(Long id) {
        Product product = new Product();
        product.setId(id);
        product.setDeleted(1);
        product.setUpdateTime(LocalDateTime.now());
        
        boolean result = updateById(product);
        if (result) {
            log.info("商品删除成功，商品ID：{}", id);
            return true;
        } else {
            log.error("商品删除失败，商品ID：{}", id);
            return false;
        }
    }

    /**
     * 分页查询商品
     */
    @Override
    public IPage<Product> getProductPage(int pageNum, int pageSize, String productName, 
                                        String category, String brand, String status) {
        Page<Product> page = new Page<>(pageNum, pageSize);
        QueryWrapper<Product> queryWrapper = new QueryWrapper<>();
        
        // 构建查询条件
        if (StringUtils.hasText(productName)) {
            queryWrapper.like("product_name", productName);
        }
        if (StringUtils.hasText(category)) {
            queryWrapper.eq("category", category);
        }
        if (StringUtils.hasText(brand)) {
            queryWrapper.eq("brand", brand);
        }
        if (StringUtils.hasText(status)) {
            queryWrapper.eq("status", status);
        }
        
        queryWrapper.eq("deleted", 0)
                   .orderByDesc("create_time");
        
        return page(page, queryWrapper);
    }

    /**
     * 根据分类查询商品列表
     */
    @Override
    public List<Product> getProductsByCategory(String category) {
        QueryWrapper<Product> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("category", category)
                   .eq("status", "ACTIVE")
                   .eq("deleted", 0)
                   .orderByDesc("create_time");
        
        return list(queryWrapper);
    }

    /**
     * 根据品牌查询商品列表
     */
    @Override
    public List<Product> getProductsByBrand(String brand) {
        QueryWrapper<Product> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("brand", brand)
                   .eq("status", "ACTIVE")
                   .eq("deleted", 0)
                   .orderByDesc("create_time");
        
        return list(queryWrapper);
    }

    /**
     * 更新商品库存
     */
    @Override
    public boolean updateProductStock(Long productId, Integer stock) {
        Product product = new Product();
        product.setId(productId);
        product.setStock(stock);
        product.setUpdateTime(LocalDateTime.now());
        
        boolean result = updateById(product);
        if (result) {
            log.info("商品库存更新成功，商品ID：{}，新库存：{}", productId, stock);
            return true;
        } else {
            log.error("商品库存更新失败，商品ID：{}", productId);
            return false;
        }
    }

    /**
     * 更新商品状态
     */
    @Override
    public boolean updateProductStatus(Long productId, String status) {
        Product product = new Product();
        product.setId(productId);
        product.setStatus(status);
        product.setUpdateTime(LocalDateTime.now());
        
        boolean result = updateById(product);
        if (result) {
            log.info("商品状态更新成功，商品ID：{}，新状态：{}", productId, status);
            return true;
        } else {
            log.error("商品状态更新失败，商品ID：{}", productId);
            return false;
        }
    }

    /**
     * 批量创建商品
     * 使用MyBatis-Plus的saveBatch方法，支持事务回滚
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean batchCreateProducts(List<Product> products) {
        if (CollectionUtils.isEmpty(products)) {
            log.warn("批量创建商品失败：商品列表为空");
            return false;
        }
        
        // 设置创建时间和默认值
        LocalDateTime now = LocalDateTime.now();
        products.forEach(product -> {
            product.setCreateTime(now);
            product.setUpdateTime(now);
            product.setDeleted(0);
        });
        
        boolean result = saveBatch(products);
        if (result) {
            log.info("批量创建商品成功，数量：{}", products.size());
        } else {
            log.error("批量创建商品失败，数量：{}", products.size());
        }
        return result;
    }

    /**
     * 批量更新商品
     * 使用MyBatis-Plus的updateBatchById方法，支持事务回滚
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean batchUpdateProducts(List<Product> products) {
        if (CollectionUtils.isEmpty(products)) {
            log.warn("批量更新商品失败：商品列表为空");
            return false;
        }
        
        // 设置更新时间
        LocalDateTime now = LocalDateTime.now();
        products.forEach(product -> product.setUpdateTime(now));
        
        boolean result = updateBatchById(products);
        if (result) {
            log.info("批量更新商品成功，数量：{}", products.size());
        } else {
            log.error("批量更新商品失败，数量：{}", products.size());
        }
        return result;
    }
}